import { apiClient } from '../config'
import type {
  Response,
  GetUserPagedListAsync,
  GetUserPagedListAsyncResponse,
  AddUserAsyncParams,
  UpdateUserAsyncParams,
  UpdateUserPwdAsyncParams,
} from '../../types/User'

/**
 * 分页查询用户列表
 * @param params 查询参数
 * @returns 用户列表响应
 */
export const getUserPagedListAsync = async (
  params: GetUserPagedListAsync,
): Promise<GetUserPagedListAsyncResponse> => {
  return await apiClient.get('/User/GetUserPagedListAsync', { params })
}

/**
 * 添加用户
 * @param params 添加用户参数
 * @returns 操作结果
 */
export const addUserAsync = async (params: AddUserAsyncParams): Promise<Response> => {
  return await apiClient.post('/User/AddUserAsync', params, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 修改用户密码
 * @param params 修改用户密码参数
 * @returns 操作结果
 */
export const updateUserPwdAsync = async (params: UpdateUserPwdAsyncParams): Promise<Response> => {
  return await apiClient.post('/User/UpdateUserPwdAsync', params, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 修改用户信息（支持文件上传）
 * @param params 修改用户参数
 * @param file 头像文件
 * @returns 操作结果
 */
export const updateUserAsync = async (
  params: UpdateUserAsyncParams,
  file?: File,
): Promise<Response> => {
  const formData = new FormData()

  // 添加用户参数到 FormData
  Object.keys(params).forEach((key) => {
    const value = params[key as keyof UpdateUserAsyncParams]
    if (value !== undefined && value !== null) {
      formData.append(key, value.toString())
    }
  })

  // 如果有文件，添加到 FormData
  if (file) {
    formData.append('file', file)
  }

  return await apiClient.post('/User/UpdateUserAsync', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

/**
 * 启用/停用用户
 * @param params 启用停用参数
 * @returns 操作结果
 */
export const updateUserStatusAsync = async (id: number): Promise<Response> => {
  return await apiClient.post('/User/UpdateUserStatusAsync', id, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 批量启用/停用用户
 * @param ids 用户ID数组
 * @returns 操作结果
 */
export const updateUsersStatusAsync = async (ids: number[]): Promise<Response> => {
  return await apiClient.post('/User/UpdateUsersStatusAsync', ids, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 用户下拉框
 * @returns 操作结果
 */
export const getUserDropdownBoxAsync = async (): Promise<Response> => {
  return await apiClient.get('/User/GetUserDropdownBoxAsync')
}

export default {
  getUserPagedListAsync,
  addUserAsync,
  updateUserAsync,
  updateUserStatusAsync,
  updateUsersStatusAsync,
  getUserDropdownBoxAsync,
  updateUserPwdAsync,
}
